package com.liveinstars.gateway.application.filter.factory;

import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Bucket;
import io.github.bucket4j.Bucket4j;
import io.github.bucket4j.Refill;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpStatus;

import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: ting
 * @date: 2019-07-18
 */
public class RateLimitByIPGatewayFilterFactory extends AbstractGatewayFilterFactory<RateLimitByIPGatewayFilterFactory.Config> {

    private static final Logger logger = LoggerFactory.getLogger(RateLimitByIPGatewayFilterFactory.class);

    private static final Map<String, Bucket> LOCAL_CACHE = new ConcurrentHashMap<>();

    public RateLimitByIPGatewayFilterFactory() {
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("capacity", "refillTokens", "refillDuration", "whiteList");
    }

    private Bucket createNewBucket(int capacity, int refillTokens, Duration refillDuration){
        Refill refill = Refill.of(refillTokens, refillDuration);
        Bandwidth limit = Bandwidth.classic(capacity, refill);
        return Bucket4j.builder().addLimit(limit).build();
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            String ip = exchange.getRequest().getHeaders().getFirst("X-Forwarded-For");
            logger.info("RateLimitByIPGatewayFilterFactory IP:{}", ip);
            if (StringUtils.isEmpty(ip)) {
                logger.error("RateLimitByIPGatewayFilterFactory ip is empty");
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }
            //白名单放行
            if (ip.contains(",")) {
                ip = ip.split(",")[0];
            }
            if (!config.getWhiteList().contains(ip)) {
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }
            Bucket bucket = LOCAL_CACHE.computeIfAbsent(ip, k -> createNewBucket(config.getCapacity(), config.getRefillTokens(), Duration.ofSeconds(config.getRefillDuration())));
            logger.info("IP:{}, 令牌桶可用的Token数量：{}", ip, bucket.getAvailableTokens());
            if (bucket.tryConsume(1)) {
                return chain.filter(exchange);
            } else {
                exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
                return exchange.getResponse().setComplete();
            }
        };
    }

    public static class Config {
        /**
         * 令牌桶大小，能装载Token的最大数量
         */
        int capacity;

        /**
         * 每次补充Token的量
         */
        int refillTokens;

        /**
         * 补充Token的时间间隔s
         */
        int refillDuration;

        /**
         * 白名单ip
         */
        String whiteList;

        public Config() {
        }

        public int getCapacity() {
            return capacity;
        }

        public Config setCapacity(int capacity) {
            this.capacity = capacity;
            return this;
        }

        public int getRefillTokens() {
            return refillTokens;
        }

        public Config setRefillTokens(int refillTokens) {
            this.refillTokens = refillTokens;
            return this;
        }

        public int getRefillDuration() {
            return refillDuration;
        }

        public String getWhiteList() {
            return whiteList;
        }

        public Config setWhiteList(String whiteList) {
            this.whiteList = whiteList;
            return this;
        }

        public Config setRefillDuration(int refillDuration) {
            this.refillDuration = refillDuration;
            return this;
        }
    }
}
